<?php

namespace App\Tables;

use Illuminate\Database\Eloquent\Model;

class AgentBalanceTransferRecord extends Model
{
    protected $table = 'agent_balance_transfer_records';

    protected $appends = [
        'agent_name',
        'agent_realname',
        'identity_card',
        'agent_level_text',
        'parent_agent_name',
        'type_text'
    ];

    /**
     * 获取代理账号
     * @return mixed
     */
    public function getAgentNameAttribute()
    {
        return $this->agent->name;
    }

    /**
     * 获取代理真实姓名
     * @return mixed
     */
    public function getAgentRealnameAttribute()
    {
        return $this->agent->realname;
    }

    /**
     * 获取代理身份证号码
     * @return mixed
     */
    public function getIdentityCardAttribute()
    {
        return $this->agent->identity_card;
    }

    /**
     * 获取上级代理名称
     * @return mixed
     */
    public function getParentAgentNameAttribute()
    {
        return $this->agent->parent_path;
    }

    /**
     * 获取代理级别
     * @return mixed
     */
    public function getAgentLevelTextAttribute()
    {
        return $this->agent->extension->agent_level_text;
    }

    /**
     * 获取资金流向类型
     * @return mixed|string
     */
    public function getTypeTextAttribute()
    {
        switch ($this->type) {
            case 'order_settlement':
                return '订单结算';
            case 'order_refund':
                return '订单退款';
            case 'withdraw':
                return '提现';
            default:
                return $this->type;
        }
    }

    /**
     * 获取代理信息
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function agent()
    {
        return $this->hasOne('App\Tables\User', 'id', 'agent_user_id');
    }


    /**
     * 获取所有下级代理
     * @param $query
     * @param $id
     * @return mixed
     */
    public function scopeOfChildren($query, $id)
    {
        return $query->whereIn('agent_user_id', function ($query) use ($id) {
            $query->select('ar.child_id as id')
                ->from('users as u')
                ->join('agent_relation as ar', 'u.id', '=', 'ar.child_id')
                ->where('u.type', 1)
                ->where('ar.parent_id', $id);
        });
    }
}
